#!/usr/bin/perl

#
# pushing local folder into Include array and including needed files
#
push(@INC,".");
use HTTP::Daemon;
use threads;
#use CGI;
do ("functions.pl" or die $!);
#
# setting up daemon and giving back PID, address and port or error in case it didnt start
#
my $d = HTTP::Daemon->new(LocalAddr => localhost, LocalPort => 9090, ReuseAddr => 1) || die "Couldn't start server! Reason: $!";
print "Serving as (".$$.") on ".$d->sockhost.":".$d->sockport."\n";
#
# looping and creating handle threads for incoming requests
#
#while (1) { #for not quiting when site is requested withou SSL
	while (my $c = $d->accept) {
		threads->create(\&handle, $c)->detach();
	}
#}
#
# getting request, splitting up GET-parameters and POST-Fields into hashs, structuring HTML output and building the body
#
sub handle {
    my $c = shift;
    my $r = $c->get_request;
    my %_GET=();
    my %_POST=();
    if ($r) {
		%_GET = &parseQueryString($r->url());
   	 	if ($ENV{'CONTENT_LENGTH'}>0) {
   	 		%_POST = &parsePostFields();	 
   	 	}
	    &structure;
	    print $c $head;
		print $c (
			'<div id="header">
				<span class="title">Xenter - Management UI</span>
			</div>
			<div id="body">
				<div id="content">
					<FORM ACTION="'.$ENV{"SCRIPT_NAME"}.'" METHOD="POST">
						<INPUT TYPE="TEXT" NAME="usr">
						<INPUT TYPE="Password" NAME="pwd">
						<INPUT TYPE="submit" value ="ok">
					</FORM>
				</div>
			</div>
			<u>Debug</u><p>get:<br />
		');
		print $c $ENV{'REQUEST_METHOD'};
   		foreach (keys(%_GET)) {
			print $c ($_ ."=".$_GET{$_}.";<p>");
		}
		foreach (keys(%_POST)) {
			print $c 'post: '.($_ ."=".$_POST{$_}.";</p>");
		}
		print $c $footer;
    }
    else {
		$c->send_error();
    }
    $c->close;
    undef($c);
}
